//
//  PGUserAccountViewModel.swift
//  PGWeibo
//
//  Created by Apple on 15/11/7.
//  Copyright © 2015年 Apple. All rights reserved.
//

import Foundation

class PGUserAccountViewModel {
    /// 单例 - 解决避免重复从沙盒加载 归档 文件，提高效率，让 access_token 便于被访问到
    static let sharedUerAccountViewModel = PGUserAccountViewModel()
    /// 用户信息
    var userAccount: PGUserAccount?
    
    var avatarUrl: NSURL {
        return NSURL(string: (userAccount?.avatar_large) ?? "")!
    }
    /// 信息保存路径
    private var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    var accessToken: String? {
        if isExpired {
            return nil
        }
        return userAccount?.access_token
    }
    /// 从本地加载用户信息
    ///
    /// - returns: userAccount
    init() {
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? PGUserAccount
        //如果过期重新授权
        if isExpired {
            userAccount = nil
        }
    }
    
}
// MARK: - 业务逻辑
extension PGUserAccountViewModel {
    //把用户信息保存到本地
    func saveUserAccount(userAccount: PGUserAccount) {
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
    }
    
    //token是否过期
    private var isExpired: Bool {
        if userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return true
        }
        return false
    }
    /// 用户是否登录
    var userLogon: Bool {
        // 1. 如果 token 有值，说明登录成功
        // 2. 如果没有过期，说明登录有效
        return userAccount?.access_token != nil && !isExpired
    }
}

// MARK: - 网络代码
extension PGUserAccountViewModel {
    
    func loadAccessToken(code: String, finished: (isSuccessed: Bool) -> ()) {
        
        //根据授权码 获得令牌
        PGNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                print(error)
                print("出错了")
                return
            }
            
            print(result!)
            //字典转模型
            self.userAccount = PGUserAccount(dict: result! as! [String : AnyObject])
//            print(self.userAccount)
            
            //获取用户信息
            self.loadUserInfo(self.userAccount!, finished: finished)
            
        }
    }
    
    private func loadUserInfo(userAccount: PGUserAccount, finished:(isSuccessed: Bool) -> ()) {
        
        PGNetworkTools.sharedTools.loadUserInfo(userAccount.uid) { (result, error) -> () in
            if error != nil {
                print("加载用户信息出错")
                return
            }
            //            print(result)
            
            // 提示：如果使用 if let / guard let 统统使用 `?`
            // 作了两个判断
            // 1. result 一定有内容
            // 2. 一定是字典
            guard let dict = result as?[String: AnyObject] else {
                print("数据格式错误")
                return
            }
            self.userAccount!.name = dict["name"] as? String
            self.userAccount!.avatar_large = dict["avatar_large"] as? String
            
            //写入到本地
            self.saveUserAccount(userAccount)
            //完成回调
            finished(isSuccessed: true)
        }
    }
    
  

}